<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-scrollbar class="w-full h-full">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="分类能耗：">
              <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="small">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="(item, index) in meterTypeList" :key="index"
                  :label="item.paramValue"
                  :value="item.paramKey">
                </el-option>
              </el-select>
              <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:16px;" @click="getList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="grid grid-cols-3 gap-4" v-loading="loading">
          <div v-for="(i, index) in list" :key="index" style="background-color:rgba(0,0,0,.1);" class="theme-front-color">
            <div class="p-3 flex items-center pb-0">
              <span class="flex-1">{{ i.meter_name }}</span>
              <span class="text-sm">{{ i.meter_code }}</span>
            </div>
            <div class="p-3 flex items-center pb-0">
              <span class="flex-1">采集时间</span>
              <span class="text-sm">{{ i.ctime }}</span>
            </div>
            <div class="p-3">
              <div v-for="(j, inx) in i.collects" :key="inx" class="flex items-center">
                <img :src="j.collect_pic" class="w-8 h-8 object-contain" />
                <span class="flex-1 ml-2">{{ j.collect_name }}</span>
                <span>{{ j.collect_value }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </d2-container>
</template>

<script>
  import d2HeaderFullscreen from '../../layout/header-aside/components/header-fullscreen'
  import { mapGetters } from 'vuex'
  import areaTree from '../energyAnalysis/compont/area_tree_onceclick'
  export default {
    name: 'energyUse',
    data() {
      return {
        socket: null,
        buildList:[],
        dataForm:{
          energyType: '',
          date:new Date(),
          dateType: 'date'
        },
        meterTypeList:[],
        loading: true,
        list: [],
      }
    },
    computed: {
      ...mapGetters('d2admin/theme', ['activeSetting'])
    },
    components: {
      areaTree,
      d2HeaderFullscreen
    },
    created() {
      this.connect();

      this.$nextTick(()=>{
        this.queryStatic("METER_TYPE",null,data=>{
          if (data && data.code === 0) {
            this.meterTypeList = data.page
            this.dataForm.energyType = data.page[0].paramKey;
            this.getList()
          } else {
            this.meterTypeList = []
          }
        });
      })
    },
    beforeDestroy() {
      if (this.socket) {
        console.log("beforeDestroy webSocketServer close");
        this.socket.close(); // 关闭连接
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.socket) {
        console.log("webSocketServer close");
        this.socket.close()
        next()
      }
    },
    methods: {
      connect() {
        let baseUrl = process.env.VUE_APP_API
        if(baseUrl.indexOf("http")!= -1) {
          console.log(11111111, baseUrl.replace('http', 'ws') + 'webSocketServer')
          this.socket = new WebSocket(baseUrl.replace('http', 'ws') + 'webSocketServer');
        }else{
          baseUrl = "ws://"+window.location.hostname+":8012/webSocketServer";
          console.log(22222, baseUrl)
          this.socket = new WebSocket(baseUrl);
        }

        this.socket.onopen = () => {
          console.log('WebSocket connection established');
        };

        this.socket.onmessage = (event) => {
        //  console.log('WebSocket onmessage',event);
          const message = JSON.parse(event.data);
          this.list = message.data && message.data.devices || []
        };

        this.socket.onerror = (error) => {
          console.error('WebSocket error:', error);
        };

        this.socket.onclose = () => {
          console.log('WebSocket connection closed');
        };
      },
      sendMessage(param) {
          //实时监测
          this.socket.send(JSON.stringify({ messType:"realtime",messContent: param }));
      },
      treeNodeChange(data){
        console.log(data)
        this.building = data
        this.getList()
      },
      getList() {
        if(this.dataForm.energyType == ''){
          return
        }
        this.loading = true
        let param = {
          buildingId: this.building,
          meterType: this.dataForm.energyType,
          meterCode: '',
          hostname: window.location.hostname
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/services/device'),
          method: 'get',
          params: this.$http.adornParams(param)
        }).then(res => {
          this.sendMessage(param)
          if (res.code === 0) {
            this.list = res.data && res.data.devices || []
          } else {
            this.$message.error(res.msg)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{paramValue,paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
    },
  }
</script>

<style>
</style>
